<?php
namespace control;
/*
*稽核计划类
*/

class checkPlanClass extends adIndexClass
{
    private const page = 'checkPlan';
    private const table = 'check_plan';
    private const title = '稽核计划';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'theme' => [
                        'name'  => "稽核主题",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'level'  => [
                        'name'  => "稽核级别",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'auditee_name'         => [
                        'name'  => '受稽核对象',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'category'          => [
                        'name'  => '稽核类别',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'audit_unit'          => [
                        'name'  => '稽核组长/稽核单位',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'selector'          => [
                        'name'  => '稽核组员',
                        'width' => 200,
                    ],
                    'plan_date'          => [
                        'name'  => '计划稽核日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    '稽核级别' => select(array("name" => "level", "option" => [1=>'内部',2=>'外部'])),
                    "稽核对象"     => text(array("name" => "auditee_name")),

                ],
                [
                    '稽核类别' => select(array("name" => "category", "option" => explode('，',para('inspectionType')))),
                    "稽核组长/稽核单位"     => text(array("name" => "audit_unit")),
                    '稽核日期'   => text(array("name" => "plan_date", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
            "auditee_name" => $this->post('auditee_name'),//稽核对象
            "audit_unit" => $this->post('audit_unit'),//稽核组长/稽核单位
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "level" => $this->post('level'),//稽核级别
            "category" => $this->post('category'),//稽核类别

        );
        $and = "";
        if ($this->post('plan_date')) {
            $and.=self::timeComparison($this->post('plan_date'),'date','plan_date');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "level":
                        $row[] = ($array['level']==1?'内部':'外部');
                        break;
                    case "selector":
                        $row[] = self::showSelectorText($array['selector']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 显示员工姓名
     * @param $selector
     * @return string
     */
    public static function showSelectorText($selector): string
    {
        $html = '';
        if (empty($selector) || is_array($selector)) {
            return $html;
        }
        $selector = array_filter(explode(';', $selector));
        foreach ($selector as $val) {
            $department = query('department', "id = '$val'");
            if ($department['id']) {
                $name = $department['name'];
                $id = $department['id'];
            } else {
                $job = query('job', "id = '$val'");
                if ($job['id']) {
                    $name = $job['name'];
                    $id = $job['id'];
                } else {
                    $staff = query('staff', "stid = '$val'");
                    $name = $staff['name'];
                    $id = $staff['stid'];
                }
            }
            if ($name) {
                $html .= $name.',';
            }
        }
        $html = rtrim($html, ',');
        return $html;
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $fileUpload = new fileUploadClass();
        if($info['level'] == 2){
            $title = "稽核单位：";
            $select = text(array('name' => 'audit_unit', 'class' => 'text', 'title' => '请填写', 'value' => $info['audit_unit']));
        }else{
            $title = "稽核组长：";
            $select = selectMultiple(array('name' => 'group_leader', 'table' => 'staff', 'sqlId' => 'stid', 'sqlField' => 'name', 'where' => "state !='离职'", 'value' => $info['group_leader'], 'title' => '请选择'));
        }
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    "<div class='small-title'>基本信息</div>"
                ],
                [
                    must . "稽核主题：" => text(["name" => "theme", 'class' => 'text', "value" => $info['theme']]),
                    must . "计划稽核日期：" => text(["name" => "plan_date", 'laydate' => [], "value" => $info['plan_date']]),
                ],
                [
                    must . "稽核级别：" => radio(["name" => "level", "change" => "switchExecute", 'value' => [1=>'内部', 2=>'外部'], "checked" => $info['level']?:1]),
                    must . "受稽核对象：" => selectMultiple(array('table' => 'department', 'multiple' => true, "title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'auditee[]', 'value' => $info['auditee'])),
                ],
                [
                    must . "稽核类别：" => select(array('name' => 'category', 'title' => '请选择', 'class' => 'select', 'value' => $info['category'], 'option' => explode('，', para('inspectionType')))),
                    must ."<span id='execute_title'>$title</span>" => "<div id='execute_select' style='width: 100%;'>$select</div>",
                ],
                [
                    "稽核组员：" => componentClass::staffSelector($info['selector'])
                ],
                [
                    "稽核内容：" => textarea(array('name' => 'text', 'class' => 'textarea', 'value' => $info['text'])),
                ],
                [
                    "<div class='small-title'>附件</div>" .
                    $fileUpload->addFileComponent($info['id'], '稽核计划', self::page, self::page . 'EditForm'),
                ],
            ],
        ]);
        $html .= <<<eof
<script>
function switchExecute(e){
     $.post(root+'control/adIndex.html?cla=checkPlan&fun=switchExecute',{level:e.value},function(res) {
            $("#execute_title").text(res.execute_title)
            $("#execute_select").html(res.execute_select)
       },'json')
}
</script>
eof;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 500, "html" => $html));
    }


    public function switchExecute()
    {
        $level = $this->post('level');
        $json = [];
        if($level == 2){
            $json['execute_title'] = "稽核单位：";
            $json['execute_select'] = text(array('name' => 'audit_unit', 'title' => '请填写', 'class' => 'text', 'value' => ''));
        }else{
            $json['execute_title'] = "稽核组长：";
            $json['execute_select'] = selectMultiple(array('name' => 'group_leader', 'table' => 'staff', 'sqlId' => 'stid', 'sqlField' => 'name', 'where' => "state !='离职'", 'value' => '', 'title' => '请选择'));
        }
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //附件
        $fileIdArr = $this->post('fileId');

        $field = [
            'theme' => $this->post('theme'),
            'plan_date' => $this->post('plan_date'),
            'level' => $this->post('level'),
            'auditee' => implode(',',(array)$this->post('auditee')),
            'auditee_name' => !static::isNull($this->post('auditee'))?self::findDepartment((array)$this->post('auditee')):'',
            'category' => $this->post('category'),
            'group_leader' => $this->post('group_leader'),
            'audit_unit' => $this->post('level')==2?$this->post('audit_unit'):(!static::isNull($this->post('group_leader'))?self::findStaff($this->post('group_leader')):''),
            'selector'       => $this->post('staff')[0]??'',//员工选择器
            'text' => $this->post('text')
        ];
        $field['member'] = implode(',',componentClass::returnStaffId($field['selector']));
        $annotation = [
            'theme' => '稽核主题',
            'plan_date' => '计划稽核日期',
            'level' => '稽核级别',
            'auditee' => '受稽核对象',
            'category' => '稽核类别',
            'audit_unit' => $field['level']==2?'稽核单位':'稽核组长',
        ];
        $rules = [
            'theme' => 'required',
            'plan_date' => 'required|date',
            'level' => 'required|numeric',
            'auditee' => 'required',
            'category' => 'required',
            'audit_unit' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'JH' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'deptName' => self::findStaffDepartment($this->control['stid']),
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 获取部门信息
     *
     * @param array|string $departmentId
     * @param string       $field
     * @return string
     */
    public static function findDepartment(array|string $departmentId, string $field = 'name'): string
    {
        $temp = '';
        if (!is_array($departmentId)) {
            if ($departmentId) {
                $info = query('department', " `id` = '$departmentId' ");
                $temp .= $info[$field];
            }
        } else {
            foreach ($departmentId as $id) {
                $temp .= self::findDepartment($id, $field) . '，';
            }
            $temp = rtrim($temp, '，');
        }
        return $temp;
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '稽核计划',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla'  => $this->get('cla'),
                            'fun'  => 'useDone',
                            'data' => ['id' => $info['id']],
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }
    /**
     * 稽核计划审批通过后通知受稽核对象部门负责人
     *
     * @param array $data
     * @return void
     */
    public function useDone(array $data)
    {
        $id     = $data['id'];
        $info   = query(self::table, " id = '$id' ");
        $audit = query('audit', " targetId = '$id' ");
        $auditee = explode(',',$info['auditee']);
        foreach ((array)$auditee as $value) {
            $department = query('department', "id = '$value'");
            if (!empty($department['manager'])) {
                //给部门负责人发送消息
                message(array(
                    "stid" => $department['manager'],
                    "type" => '稽核计划',
                    "typeId" => $audit['id'],
                    "text" => "您所负责的部门有稽核计划审批通过了",
                ));
            }
        }

    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );
            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {

                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($button, $this->auditButton($info));


            /*******附件****************/
            $fileCollection = fileUploadClass::showFile($info['id'], '稽核计划');
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "稽核主题" => $info['theme'],
                        "计划稽核日期" => $info['plan_date'],
                        "受稽核对象" => $info['auditee_name'],
                        "稽核级别" => $info['level']==1?'内部':'外部',
                    ),
                    array(
                        "稽核类别" => $info['category'],
                        $info['level']==1?'稽核组长':'稽核单位' => $info['audit_unit'],
                    ),
                    array(
                        "稽核组员" => componentClass::showSelector($info['selector']),
                    ),
                    array(
                        "稽核内容" => pre($info['text']),
                    ),
                ),
                "附件" => array(
                    array(
                        $fileCollection
                    ),
                ),
                "系统信息" => array(

                    array(
                        "单据编号" => $info['orderNo'],
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
                    ),
                    array(
                        "状态" => $info['state'],
                    ),
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id'])
                    )
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }



    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //删除audit表记录
                    delete(array('table'=>'audit','where'=>"targetId = '$id'"));
                    $all = find(array('table'=>'file','where'=>"targetId = '$id'"));
                    foreach ($all['array'] as $val){
                        fileDelete($val['src']);
                        delete(array("table" =>'file', "where" => " id = '$val[id]' "));
                    }
                    //删除待办事项
                    delete(array("table" => "backlog","where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message","where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }




}

